<template>
  <Form class="xtx-form" v-slot="{errors}" :validation-schema="rules" ref="fm">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field
        class="input"
        v-model="userInfo.account"
        name="account"
        :class="{err:errors.account}"
        type="text"
        placeholder="请输入用户名"
         />
      </div>
      <div class="error" v-show="errors.account">{{errors.account}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
        class="input"
        type="text"
        v-model="userInfo.mobile"
        name="mobile"
        :class="{err:errors.mobile}"
        placeholder="请输入手机号"
         />
      </div>
      <div class="error" v-show="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
        class="input"
        type="text"
        v-model="userInfo.code"
        name="code"
        :class="{err:errors.code}"
        placeholder="请输入验证码"
        />
        <span class="code" @click="verificationCode">
           {{ count === 0 ? "发送验证码" : `${count}秒后发送` }}
          </span>
      </div>
      <div class="error" v-show="errors.code">{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
        class="input"
        v-model="userInfo.password"
        name="password"
        :class="{err:errors.password}"
        type="password"
        placeholder="请输入密码"
        />
      </div>
      <div class="error" v-show="errors.password">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
        class="input"
        v-model="userInfo.rePassword"
        name="rePassword"
        :class="{err:errors.rePassword}"
        type="password"
        placeholder="请确认密码1" />
      </div>
      <div class="error" v-show="errors.rePassword">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" class="submit">立即提交</a>
  </Form>
</template>

<script>
import schema from '@/utils/vee-validate-schema'
import { useCountDown } from '@/hooks'
import { Form, Field } from 'vee-validate'
import { userQQPatchLogin, userQQPatchCode } from '@/api/user'
import { ref } from 'vue'
import { message } from '@/components/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
const userUser = () => {
  const userInfo = ref({
    account: null,
    mobile: null,
    code: null,
    password: null,
    rePassword: null
  })
  const rules = {
    account: schema.accountApi,
    mobile: schema.mobile,
    code: schema.code,
    password: schema.password,
    rePassword: schema.rePassword
  }
  return { userInfo, rules }
}

const useSendCode = (userInfo) => {
  const fm = ref()
  const store = useStore()
  const { count, start } = useCountDown(60)
  const verificationCode = async () => {
    const valueMobile = schema.mobile(userInfo.mobile)
    if (valueMobile === true) {
      try {
        if (count.value === 0) {
          await userQQPatchCode(userInfo.mobile)
          // 登录成功之后=》合并之前本地购物车数据，到当前登录人名下
          await store.dispatch('cart/mergeCartAction')
          message({ type: 'success', text: '发送成功！' })
          start()
        }
      } catch (error) {
        message({ type: 'error', text: error.response.data.message })
      }
    } else {
      // 手机号格式错=>js触发错误信息的显示
      fm.value.setFieldError('mobile', valueMobile)
    }
  }
  return { fm, count, verificationCode }
}

// 注册账号并绑定QQ
const useSubmit = (fm, props, userInfo) => {
  const store = useStore()
  const router = useRouter()
  // 点击注册账号事件回调
  const submit = async () => {
    /**
     * 1. 表单整体校验
     * 2. 校验通过执行绑定=》获取登录人信息存储=》跳首页
     */
    const res = await fm.value.validate()
    // console.log(res)
    if (res.valid) {
      try {
        // 校验通过
        const { result } = await userQQPatchLogin({
          unionId: props.unionId,
          ...userInfo.value
        })
        // 存储当前登录人信息
        store.commit('user/setProfile', result)
        message({ type: 'success', text: '注册成功！' })
        router.replace('/')
      } catch (error) {
        message({ type: 'error', text: '注册失败！' })
      }
    }
  }

  return { submit }
}
export default {
  name: 'CallbackPatch',
  components: {
    Form,
    Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const { userInfo, rules } = userUser()
    const { fm, count, start } = useSendCode()
    const { submit } = useSubmit(fm, props, userInfo)
    return { userInfo, rules, fm, count, start, submit }
  }

}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
